﻿#include "service.h"
#include <QDebug>
#include <QEventLoop>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonValue>
#include <QFile>
#include <encode.h>
#include <QDateTime>

Service::Service(QObject *parent) : QObject(parent)
{
    load();
}

QString Service::getAccessToken(const QString &ak, const QString &sk)
{  
    this->ak = ak;
    this->sk = sk;

    if( QDateTime::currentDateTimeUtc().toTime_t() < tocken_in )
    {
        return tocken;
    }

    QByteArray args;
    args.append("grant_type=client_credentials");
    args.append("&client_id=" + ak);
    args.append("&client_secret=" + sk);

    QNetworkRequest request;
    request.setUrl(QUrl("https://aip.baidubce.com/oauth/2.0/token"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    request.setHeader(QNetworkRequest::ContentLengthHeader, args.size() );

    QEventLoop loop;
    connect(&manger, &QNetworkAccessManager::finished, this, [&](){ loop.quit(); } );
    QString repData;

    connect( &manger, &QNetworkAccessManager::finished, this, [&](QNetworkReply *reply){
        QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        if(statusCode.isValid())
        {
            qDebug() << "status code=" << statusCode.toInt();
        }

        QNetworkReply::NetworkError err = reply->error();
        if(err != QNetworkReply::NoError)
        {
            qDebug() << "Failed: " << reply->errorString();
        }
        else
        {
            // 获取返回内容
            repData = reply->readAll();
            QJsonDocument doc = QJsonDocument::fromJson(repData.toLatin1());
            tocken = doc.object().value("access_token").toString().toLatin1();
            tocken_in = doc.object().value("expires_in").toVariant().toLongLong() \
                    + QDateTime::currentDateTimeUtc().toTime_t(); //加上当前时间， 就把失效时间计算出来了
            save();    //数据保存到文件中
        }

    });

    manger.post(request, args);
    loop.exec();

    return tocken;
}

qint64 Service::load()
{
    TOCKEN T;
    QFile f("tocken");
    f.open( QIODevice::ReadOnly );
    qint64 len = f.read( reinterpret_cast<char*>(&T), sizeof (T) );
    f.close();

    tocken = T.tocken;
    tocken_in = T.tocken_in;

    qDebug() << "读取出来的数据:" << T.tocken << T.tocken_in;
    return len;
}

qint64 Service::save()
{
    TOCKEN T;
    memset( T.tocken, 0, 1024 );
    memcpy( T.tocken, tocken.data(), tocken.size() );
    T.tocken_in = tocken_in;
    qDebug() << "保存的tocken_in:" << tocken_in;

    QFile f("tocken");
    f.open( QIODevice::WriteOnly );
    qint64 len = f.write( reinterpret_cast<char*>(&T), sizeof (T) );
    f.close();
    return len;
}

QStringList Service::getCardId(const QString& fileName)
{
    //说明tocken已经失效
    if( tocken_in > QDateTime::currentDateTimeUtc().toTime_t() )
    {
        getAccessToken(ak, sk);
    }

    QNetworkRequest request;
    request.setUrl(QUrl("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate"));
    QFile file(fileName);
    file.open(QIODevice::ReadOnly);
    QByteArray img = Encode::urlEncode(file.readAll().toBase64());

    QByteArray args;
    args.append("access_token=" + tocken);
    args.append("&image=" + img);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    request.setHeader(QNetworkRequest::ContentLengthHeader, args.size() );


    QEventLoop loop;
    connect( &manger, &QNetworkAccessManager::finished, this, [&](){loop.quit();} );

    QStringList reslutList;
    connect( &manger, &QNetworkAccessManager::finished, this, [&](QNetworkReply *reply){
        QByteArray data = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(data);
        QJsonObject result = doc.object().value("words_result").toObject();
        reslutList.clear();
        reslutList << result.value("color").toString();
        reslutList << result.value("number").toString();

    });

    manger.post(request, args);
    loop.exec();
    return reslutList;
}
